package com.maimao.user.service.sys;

import com.maimao.core.constant.Constants;
import com.maimao.core.exception.MaiMaoDaoException;
import com.maimao.core.model.auth.AuthUser;
import com.maimao.core.utils.DateUtils;
import com.maimao.model.user.sys.Department;
import com.maimao.user.mapper.sys.DepartmentMapper;
import com.maimao.user.mapper.sys.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author MaoLin Wang
 * @date 2020/12/2 4:29 下午
 */
@Service
public class DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private SysUserMapper sysUserMapper;


    public List<Department> departmentTree() {
        List<Department> parentDeparts = departmentMapper.selectTree(0);
        return parentDeparts;
    }

    public List<Department> getChild1(Integer parentId) {
        return departmentMapper.selectByParentId(parentId);
    }

    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public boolean add(Department addData, AuthUser authUser) {
        Integer parentId = addData.getParentId();
        Department parent = null;
        if (parentId != 0) {
            //判断父部门是否存在
            parent = departmentMapper.selectByIdSimple(parentId);
            if (parent == null) {
                return false;
            }
        }
        addData.setCreateTime(DateUtils.now());
        addData.setCreateUser(Integer.valueOf(authUser.getId()));
        addData.setStatus(Constants.STATUS_1);
        departmentMapper.insert(addData);
        addData.setPath(parentId == 0 ? addData.getId() + "" : parent.getPath() + "_" + addData.getId());
        departmentMapper.updateCus(addData);

        return true;
    }


    /**
     * 修改部门 目前只支持修改部门名 不支持修改部门层级
     * @param department
     * @param authUser
     * @return
     */
    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public boolean update(Department department, AuthUser authUser) {
        if (department.getParentId() != 0) {
            //判断父部门是否存在
            Department data = departmentMapper.selectByIdSimple(department.getParentId());
            if (data == null) {
                return false;
            }
        }
        departmentMapper.updateCus(department);
        return true;
    }
}
